/**
 * Created by Administrator on 2017/7/19.
 */

const variable = require('../config/variable.js');
const log = require('../util/log.js');
const util = require('../util/util.js');
const blued = require('./blued.js');
const tourist = require('./tourist.js');
const lovelive = require('./lovelive.js');

var login = module.exports;

login.run = function (req, res) {
    res.header('Access-Control-Allow-Origin', '*');
    var data = util.getRequestParam(req);
    //if (!data.platform) {
    //    data.platform = 'ios';
    //}
    if (data.proxy=="tourist"){
        login.tourist(data.account, data.password, data.platform, function (err1, res1) {
            login.result(res, err1, res1);
        });
        return;
    }
    
    if(data.proxy=="lovelive"){
        //爱生活登陆
        login.lovelive(data.access_token,data.groupid,data.platform, function (err1, res1) {
            login.result(res, err1, res1, data);
        });
        return 
    }

    if (data.proxy=="blued") {
        login.blued(data.access_token, data.expire, data.platform, function (err1, res1) {
            login.result(res, err1, res1);
        }); 
        return 
    }
    
};
login.result = function (res, err, data) {
    var result = {};
    if (err != null) {
        result.code = 101;
        result.msg = '发生了不明的错误';
        res.send(result).end();
        return false;
    }
    if (data.error) {
        result.code = data.code;
        result.msg = data.msg;
        res.send(result).end();
        return false;
    }
    var randGate = Math.floor(Math.random() * variable.gate.length);
    result.code = 200;
    result.token = data.token;
    result.host = variable.gate[randGate].host;
    result.port = variable.gate[randGate].port;
    if (data.account) {
        result.isReg = true;
        result.account = data.account;
        result.password = data.password;
    }
    res.send(result).end();
    return false;
};
login.tourist = function (account, password, platform, cb) {
    var touristClass = new tourist(account, password, platform);
    touristClass.run(function (err, res) {
        cb(err, res);
    });
};
login.blued = function (token, expire, platform, cb) {
    var bluedClass = new blued(token, expire, platform);
    bluedClass.run(function (err, res) {
        cb(err, res);
    });
};
login.lovelive = function (token, groupid, platform, cb) { 
    let loveliveClass = new lovelive(token,groupid, platform);
    loveliveClass.run(function (err, res) {
        cb(err, res);
    });
};